package com.example.huajia.wx.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.huajia.wx.common.util.SpringContextHolder;
import com.example.huajia.wx.db.dao.ChatmsgDao;
import com.example.huajia.wx.db.dao.TbActivityDao;
import com.example.huajia.wx.db.pojo.TbChatmsg;
import com.example.huajia.wx.service.ActivityService;
import com.example.huajia.wx.service.ChatMsgService;
import com.example.huajia.wx.service.UserService;
import com.example.huajia.wx.service.impl.ActivityServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;


@Component
@ServerEndpoint("/websocket/{onlineUser}")
public class WebSocketServerEndpoint {


    private static final ChatmsgDao chatmsgDao = SpringContextHolder.getBean(ChatmsgDao.class);


    private static final Logger logger = LoggerFactory.getLogger(WebSocketServerEndpoint.class);

    /**
     * 所有在线用户的Session
     */
    private static final Set<Session> onlineUsers = Collections.synchronizedSet(new HashSet<Session>());


    @OnOpen
    public void onOpen(Session session, @PathParam("onlineUser") String onlineUser) {
        logger.info("WebSocket连接成功，用户{}", onlineUser);
        onlineUsers.add(session);

        // 给用户发送未读消息
        List<TbChatmsg> chatMsgs = chatmsgDao.selectUnreadMsgByUser(onlineUser);
        System.out.println("chatmsgDao ====> " + chatmsgDao);
        for (TbChatmsg chatMsg : chatMsgs) {
            JSONObject json = new JSONObject();
            json.put("id", chatMsg.getId());
            json.put("from", chatMsg.getFrom());
            json.put("to", chatMsg.getTo());
            json.put("content", chatMsg.getContent());
            json.put("sendTime", chatMsg.getSendTime().getTime());

            session.getAsyncRemote().sendText(chatMsg.getContent());

            // 标记为已读
            chatMsg.setStatus(1);
            chatmsgDao.updateByPrimaryKey(chatMsg);
        }
    }


    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        logger.info("接收到一条消息：{}", message);

        JSONObject json = JSON.parseObject(message);
        String from = json.getString("from");
        String from_name = json.getString("from_name");
        String to = json.getString("to");
        String to_name = json.getString("to_name");
        String content = json.getString("content");

        // 存储到数据库
        String id = "";
        if (!content.isEmpty()) {
            id = saveMessage(from, from_name, to, to_name, content);
        }

        // 是否要发给所有在线用户
        boolean sendToAll = json.getBooleanValue("sendToAll");
        if (sendToAll) {
            // 向所有在线用户广播消息
            for (Session s : onlineUsers) {
                s.getAsyncRemote().sendText(message);
            }
        } else {
            // 发给指定用户
            to = json.getString("to");
            Session targetSession = getSessionByUser(to);
            if (targetSession != null) {
//                targetSession.getAsyncRemote().sendText(message);
                targetSession.getAsyncRemote().sendText(content);
                // 标记为已读
                if (!id.isEmpty()) {
                    TbChatmsg chatMsg = new TbChatmsg();
                    chatMsg.setStatus(1);
                    chatMsg.setId(id);
                    chatmsgDao.updateByPrimaryKey(chatMsg);
                }

            }
        }
    }

    /**
     * 根据用户ID查找对应的Session
     */
    private Session getSessionByUser(String user) {
        for (Session session : onlineUsers) {
            if (user.equals(session.getPathParameters().get("onlineUser"))) {
                return session;
            }
        }
        return null;
    }


    @OnClose
    public void onClose(Session session, @PathParam("onlineUser") String onlineUser) {
        logger.info("WebSocket连接关闭，用户{}", onlineUser);
        onlineUsers.remove(session);
    }

    @OnError
    public void onError(Throwable throwable, Session session) {
        logger.error("WebSocket发生错误", throwable);
        onlineUsers.remove(session);
        try {
            session.close();
        } catch (IOException e) {
            logger.error("关闭WebSocket Session失败", e);
        }
    }

    /**
     * 将消息存储到数据库中
     */
    private String saveMessage(String from, String from_name, String to, String to_name, String content) {
        TbChatmsg msg = new TbChatmsg();
        String id = UUID.randomUUID().toString().replace("-", "");
        msg.setId(id);
        msg.setFrom(from);
        msg.setFromName(from_name);
        msg.setTo(to);
        msg.setToName(to_name);
        msg.setContent(content);
        chatmsgDao.insert(msg);
        return id;
    }

}
